"""
Folder Management View for Desktop Application
桌面应用文件夹管理界面
"""

import logging
from typing import Optional, Dict, Any, List
import asyncio

import flet as ft
from flet import (
    Page,
    Container,
    Column,
    Row,
    Text,
    TextField,
    ElevatedButton,
    IconButton,
    Icon,
    Icons,
    Colors,
    Card,
    Divider,
    ListView,
    AlertDialog,
    PopupMenuButton,
    PopupMenuItem,
    DragTarget,
    DragTargetEvent,
    Draggable,
)

from ..services.api_client import APIClient
from ..core.state_manager import StateManager

logger = logging.getLogger(__name__)


class FolderManagementView:
    """文件夹管理界面视图类"""
    
    def __init__(self, page: Page, state_manager: StateManager, api_client: APIClient):
        self.page = page
        self.state_manager = state_manager
        self.api_client = api_client
        
        # 界面组件
        self.content: Optional[Container] = None
        self.main_column: Optional[Column] = None
        self.folder_tree: Optional[ListView] = None
        self.content_list: Optional[ListView] = None
        
        # 状态
        self.folder_tree_data: List[Dict[str, Any]] = []
        self.selected_folder: Optional[Dict[str, Any]] = None
        self.dragged_item: Optional[Dict[str, Any]] = None
        self.is_loading: bool = False
        
    async def show(self) -> None:
        """显示文件夹管理界面"""
        try:
            logger.info("Showing folder management view")
            
            # 创建界面
            await self._create_interface()
            
            # 加载文件夹数据
            await self.load_folder_tree()
            
            logger.info("Folder management view shown successfully")
            
        except Exception as e:
            logger.error(f"Failed to show folder management view: {e}")
            raise
    
    def get_content(self) -> Container:
        """获取界面内容"""
        return self.content
    
    async def _create_interface(self) -> None:
        """创建界面"""
        # 创建工具栏
        toolbar = self._create_toolbar()
        
        # 创建主要内容区域
        main_content = self._create_main_content()
        
        # 创建主列
        self.main_column = Column([
            # 标题区域
            Container(
                content=Column([
                    Text("文件夹管理", size=28, weight=ft.FontWeight.BOLD),
                    Text(
                        "组织和管理您的内容文件夹",
                        size=16,
                        color=colors.SECONDARY,
                    ),
                ], spacing=5),
                padding=ft.padding.only(bottom=20),
            ),
            
            # 工具栏
            toolbar,
            
            # 主要内容区域
            main_content,
        ],
        spacing=20,
        scroll=ft.ScrollMode.AUTO,
        )
        
        # 创建主内容容器
        self.content = Container(
            content=self.main_column,
            padding=20,
            expand=True,
        )
    
    def _create_toolbar(self) -> Container:
        """创建工具栏"""
        # 新建文件夹按钮
        new_folder_button = ElevatedButton(
            text="新建文件夹",
            icon=icons.CREATE_NEW_FOLDER,
            on_click=self._on_new_folder_click,
        )
        
        # 刷新按钮
        refresh_button = IconButton(
            icon=icons.REFRESH,
            tooltip="刷新文件夹",
            on_click=self._on_refresh_click,
        )
        
        # 展开/折叠按钮
        expand_all_button = TextButton(
            text="全部展开",
            on_click=self._on_expand_all_click,
        )
        
        collapse_all_button = TextButton(
            text="全部折叠",
            on_click=self._on_collapse_all_click,
        )
        
        return Container(
            content=Row([
                new_folder_button,
                refresh_button,
                expand_all_button,
                collapse_all_button,
            ], spacing=10),
            padding=20,
            bgcolor=colors.SURFACE_VARIANT,
            border_radius=8,
        )
    
    def _create_main_content(self) -> Row:
        """创建主要内容区域"""
        # 左侧：文件夹树
        folder_tree_container = Container(
            content=self._create_folder_tree_area(),
            width=300,
            bgcolor=colors.SURFACE,
            border_radius=8,
            padding=10,
        )
        
        # 右侧：内容列表
        content_list_container = Container(
            content=self._create_content_list_area(),
            expand=True,
            bgcolor=colors.SURFACE,
            border_radius=8,
            padding=10,
        )
        
        return Row([
            folder_tree_container,
            content_list_container,
        ], spacing=15, expand=True)
    
    def _create_folder_tree_area(self) -> Column:
        """创建文件夹树区域"""
        # 创建文件夹列表视图替代树视图
        self.folder_tree = ListView(
            spacing=5,
            padding=5,
            expand=True,
        )
        
        return Column([
            Text("文件夹", size=18, weight=ft.FontWeight.BOLD),
            Divider(),
            self.folder_tree,
        ], spacing=10, expand=True)
    
    def _create_content_list_area(self) -> Column:
        """创建内容列表区域"""
        # 内容列表标题
        content_title = Row([
            Text("内容列表", size=18, weight=ft.FontWeight.BOLD),
            Text("(选择文件夹查看内容)", size=14, color=colors.SECONDARY),
        ], spacing=5)
        
        # 创建内容列表视图
        self.content_list = ListView(
            spacing=10,
            padding=10,
            expand=True,
        )
        
        return Column([
            content_title,
            Divider(),
            self.content_list,
        ], spacing=10, expand=True)
    
    # 业务逻辑
    async def load_folder_tree(self) -> None:
        """加载文件夹树"""
        try:
            logger.info("Loading folder tree")
            self._set_loading_state(True)
            
            # 从状态管理器获取文件夹树
            folder_tree = await self.state_manager.get_folder_tree()
            
            if not folder_tree:
                # 从API加载文件夹树
                response = await self.api_client.get_folder_tree()
                
                if response.get("success"):
                    folder_tree = response.get("data", [])
                    await self.state_manager.set_folder_tree(folder_tree)
            
            self.folder_tree_data = folder_tree
            await self._update_folder_tree_display()
            
            logger.info(f"Folder tree loaded: {len(folder_tree)} folders")
            
        except Exception as e:
            logger.error(f"Failed to load folder tree: {e}")
            self._show_error(f"加载文件夹失败: {e}")
            
        finally:
            self._set_loading_state(False)
    
    async def refresh_folder_tree(self) -> None:
        """刷新文件夹树"""
        await self.load_folder_tree()
    
    async def _update_folder_tree_display(self) -> None:
        """更新文件夹列表显示"""
        try:
            self.folder_tree.controls.clear()
            
            if not self.folder_tree_data:
                # 显示空状态
                empty_state = Container(
                    content=Column([
                        Icon(icons.FOLDER_OPEN, size=64, color=colors.SECONDARY),
                        Text("暂无文件夹", size=16, weight=ft.FontWeight.BOLD),
                        Text("点击上方按钮创建新文件夹", size=14, color=colors.SECONDARY),
                    ],
                    spacing=15,
                    horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                    alignment=ft.MainAxisAlignment.CENTER,
                    ),
                    padding=40,
                    alignment=ft.alignment.center,
                )
                self.folder_tree.controls.append(empty_state)
            else:
                # 构建文件夹列表（扁平化显示）
                await self._build_folder_list(self.folder_tree_data)
            
            self.page.update()
            
        except Exception as e:
            logger.error(f"Failed to update folder list display: {e}")

    async def _build_folder_list(self, folders: List[Dict[str, Any]], level: int = 0) -> None:
        """构建文件夹列表（支持层级缩进）"""
        for folder in folders:
            folder_id = folder.get("id", "")
            folder_name = folder.get("name", "未命名文件夹")
            folder_type = folder.get("folder_type", "user")
            content_count = folder.get("content_count", 0)
            children = folder.get("children", [])
            
            # 选择图标
            icon = {
                "system": icons.FOLDER_SPECIAL,
                "user": icons.FOLDER,
                "shared": icons.FOLDER_SHARED,
                "archive": icons.ARCHIVE,
            }.get(folder_type, icons.FOLDER)
            
            # 创建文件夹项
            folder_item = Container(
                content=Row([
                    Container(width=level * 20),  # 缩进表示层级
                    Icon(icon, size=20, color=colors.PRIMARY),
                    Text(folder_name, expand=True),
                    Badge(
                        content=Text(str(content_count)),
                        visible=content_count > 0,
                    ),
                ], spacing=10),
                padding=8,
                border_radius=6,
                bgcolor=colors.SURFACE_CONTAINER_HIGHEST,
                on_click=lambda e, f=folder: asyncio.create_task(self._on_folder_select(e, f)),
                ink=True,
            )
            
            # 添加长按事件
            folder_item.on_long_press = lambda e, f=folder: asyncio.create_task(self._on_folder_long_press(f))
            
            self.folder_tree.controls.append(folder_item)
            
            # 递归添加子文件夹
            if children:
                await self._build_folder_list(children, level + 1)
    
    def _add_folder_context_menu(self, folder: Dict[str, Any]) -> None:
        """添加文件夹右键菜单（占位符）"""
        # 这里应该实现真正的右键菜单
        # Flet的右键菜单支持有限，这里用长按来模拟
        # 当前功能由 _on_folder_long_press 处理
        pass
        
    async def load_folder_contents(self, folder_id: str) -> None:
        """加载文件夹内容"""
        try:
            logger.info(f"Loading contents for folder: {folder_id}")
            self._set_loading_state(True)
            
            # 从API获取文件夹内容
            response = await self.api_client.get_folder(
                folder_id=folder_id,
                include_contents=True
            )
            
            if response.get("success"):
                contents = response.get("data", {}).get("contents", [])
                await self._update_content_list_display(contents)
                
                logger.info(f"Folder contents loaded: {len(contents)} items")
            else:
                self._show_error("加载文件夹内容失败")
                
        except Exception as e:
            logger.error(f"Failed to load folder contents: {e}")
            self._show_error(f"加载文件夹内容失败: {e}")
            
        finally:
            self._set_loading_state(False)
    
    async def _update_content_list_display(self, contents: List[Dict[str, Any]]) -> None:
        """更新内容列表显示"""
        try:
            self.content_list.controls.clear()
            
            if not contents:
                # 显示空状态
                empty_state = Container(
                    content=Column([
                        Icon(icons.FOLDER_OPEN, size=64, color=colors.SECONDARY),
                        Text("此文件夹暂无内容", size=16, weight=ft.FontWeight.BOLD),
                        Text("您可以在此文件夹中创建新内容", size=14, color=colors.SECONDARY),
                    ],
                    spacing=15,
                    horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                    alignment=ft.MainAxisAlignment.CENTER,
                    ),
                    padding=40,
                    alignment=ft.alignment.center,
                )
                self.content_list.controls.append(empty_state)
            else:
                # 显示内容列表
                for content in contents:
                    self.content_list.controls.append(self._create_content_item(content))
            
            self.page.update()
            
        except Exception as e:
            logger.error(f"Failed to update content list display: {e}")
    
    def _create_content_item(self, content: Dict[str, Any]) -> Container:
        """创建内容项"""
        content_id = content.get("id", "")
        title = content.get("title", "未命名内容")
        content_type = content.get("content_type", "unknown")
        status = content.get("status", "unknown")
        created_at = content.get("created_at", "")
        file_size = content.get("file_size_readable", "--")
        thumbnail_url = content.get("thumbnail_url", "")
        
        # 内容类型图标
        type_icon = {
            "image": icons.IMAGE,
            "video": icons.VIDEO_LIBRARY,
            "audio": icons.AUDIOTRACK,
            "text": icons.TEXT_FIELDS,
        }.get(content_type, icons.HELP_OUTLINE)
        
        # 状态颜色
        status_color = {
            "completed": colors.GREEN,
            "processing": colors.ORANGE,
            "pending": colors.BLUE,
            "failed": colors.RED,
        }.get(status, colors.GREY)
        
        return Container(
            content=Row([
                # 缩略图或图标
                Container(
                    content=Image(
                        src=thumbnail_url,
                        fit=ft.ImageFit.COVER,
                        width=60,
                        height=60,
                        border_radius=8,
                    ) if thumbnail_url else Container(
                        content=Icon(type_icon, size=32, color=colors.PRIMARY),
                        alignment=ft.alignment.center,
                        width=60,
                        height=60,
                        bgcolor=colors.SURFACE_VARIANT,
                        border_radius=8,
                    ),
                    margin=ft.margin.only(right=15),
                ),
                
                # 内容信息
                Column([
                    Row([
                        Text(title, size=16, weight=ft.FontWeight.BOLD, expand=True),
                        Badge(
                            content=Text(status, size=11),
                            bgcolor=status_color,
                        ),
                    ], spacing=10),
                    Row([
                        Icon(type_icon, size=16, color=colors.SECONDARY),
                        Text(f"• {file_size}", size=12, color=colors.SECONDARY),
                        Text(f"• {created_at[:10] if created_at else '未知'}", size=12, color=colors.SECONDARY),
                    ], spacing=5),
                ], expand=True, spacing=5),
                
                # 操作按钮
                Row([
                    IconButton(
                        icon=icons.VISIBILITY,
                        tooltip="预览",
                        on_click=lambda e, cid=content_id: self._on_preview_click(cid),
                    ),
                    IconButton(
                        icon=icons.DOWNLOAD,
                        tooltip="下载",
                        on_click=lambda e, cid=content_id: self._on_download_click(cid),
                    ),
                    IconButton(
                        icon=icons.DELETE,
                        tooltip="删除",
                        on_click=lambda e, cid=content_id: self._on_delete_click(cid),
                    ),
                ], spacing=5),
            ], spacing=10, alignment=ft.MainAxisAlignment.START),
            padding=15,
            bgcolor=colors.SURFACE,
            border_radius=8,
            on_click=lambda e, c=content: self._on_content_select(c),
            ink=True,
        )
    
    # 事件处理
    async def _on_folder_select(self, e, folder_data: Dict[str, Any]) -> None:
        """文件夹选择事件"""
        try:
            self.selected_folder = folder_data
            
            # 更新状态管理器
            await self.state_manager.set_selected_folder(folder_data)
            
            # 加载文件夹内容
            folder_id = folder_data.get("id", "")
            if folder_id:
                await self.load_folder_contents(folder_id)
            
            logger.info(f"Folder selected: {folder_data.get('name')}")
            
        except Exception as e:
            logger.error(f"Folder selection error: {e}")
    
    # _on_folder_expand 已移除，因为不再使用 TreeView
    
    async def _on_folder_long_press(self, folder: Dict[str, Any]) -> None:
        """文件夹长按事件"""
        # 显示文件夹操作菜单
        await self._show_folder_actions_menu(folder)
    
    async def _on_content_select(self, content: Dict[str, Any]) -> None:
        """内容选择事件"""
        try:
            await self.state_manager.set_selected_content(content)
            logger.info(f"Content selected: {content.get('title')}")
            
        except Exception as e:
            logger.error(f"Content selection error: {e}")
    
    async def _on_preview_click(self, content_id: str) -> None:
        """预览按钮点击"""
        try:
            content = await self.api_client.get_content(content_id)
            if content.get("success"):
                await self._show_content_preview(content.get("data", {}))
            else:
                self._show_error("获取内容详情失败")
                
        except Exception as e:
            logger.error(f"Preview click error: {e}")
            self._show_error(f"预览失败: {e}")
    
    async def _on_download_click(self, content_id: str) -> None:
        """下载按钮点击"""
        try:
            def confirm_download(confirmed):
                if confirmed:
                    asyncio.create_task(self._perform_download(content_id))
            
            self._show_confirm_dialog(
                title="确认下载",
                content="确定要下载这个内容吗？",
                on_confirm=confirm_download
            )
            
        except Exception as e:
            logger.error(f"Download click error: {e}")
            self._show_error(f"下载失败: {e}")
    
    async def _on_delete_click(self, content_id: str) -> None:
        """删除按钮点击"""
        try:
            def confirm_delete(confirmed):
                if confirmed:
                    asyncio.create_task(self._perform_delete(content_id))
            
            self._show_confirm_dialog(
                title="确认删除",
                content="确定要删除这个内容吗？此操作无法撤销。",
                on_confirm=confirm_delete
            )
            
        except Exception as e:
            logger.error(f"Delete click error: {e}")
            self._show_error(f"删除失败: {e}")
    
    # 文件夹操作
    async def _on_new_folder_click(self, e) -> None:
        """新建文件夹按钮点击"""
        await self._show_new_folder_dialog()
    
    async def _on_refresh_click(self, e) -> None:
        """刷新按钮点击"""
        await self.refresh_folder_tree()
    
    async def _on_expand_all_click(self, e) -> None:
        """全部展开按钮点击"""
        # TODO: 实现全部展开功能
        self._show_info("全部展开功能开发中...")
    
    async def _on_collapse_all_click(self, e) -> None:
        """全部折叠按钮点击"""
        # TODO: 实现全部折叠功能
        self._show_info("全部折叠功能开发中...")
    
    async def _on_rename_folder(self, folder: Dict[str, Any]) -> None:
        """重命名文件夹"""
        await self._show_rename_folder_dialog(folder)
    
    async def _on_delete_folder(self, folder: Dict[str, Any]) -> None:
        """删除文件夹"""
        try:
            def confirm_delete(confirmed):
                if confirmed:
                    asyncio.create_task(self._perform_delete_folder(folder))
            
            self._show_confirm_dialog(
                title="确认删除文件夹",
                content=f"确定要删除文件夹 '{folder.get('name')}' 吗？\n注意：文件夹内的内容不会被删除，会移动到根目录。",
                on_confirm=confirm_delete
            )
            
        except Exception as e:
            logger.error(f"Delete folder error: {e}")
            self._show_error(f"删除文件夹失败: {e}")
    
    async def _on_folder_properties(self, folder: Dict[str, Any]) -> None:
        """显示文件夹属性"""
        await self._show_folder_properties_dialog(folder)
    
    async def _show_folder_actions_menu(self, folder: Dict[str, Any]) -> None:
        """显示文件夹操作菜单"""
        # TODO: 实现右键菜单
        self._show_info(f"文件夹操作: {folder.get('name')}")
    
    async def _show_new_folder_dialog(self) -> None:
        """显示新建文件夹对话框"""
        # TODO: 实现新建文件夹对话框
        self._show_info("新建文件夹功能开发中...")
    
    async def _show_rename_folder_dialog(self, folder: Dict[str, Any]) -> None:
        """显示重命名文件夹对话框"""
        # TODO: 实现重命名文件夹对话框
        self._show_info("重命名文件夹功能开发中...")
    
    async def _show_folder_properties_dialog(self, folder: Dict[str, Any]) -> None:
        """显示文件夹属性对话框"""
        # TODO: 实现文件夹属性对话框
        self._show_info("文件夹属性功能开发中...")
    
    async def _perform_delete_folder(self, folder: Dict[str, Any]) -> None:
        """执行删除文件夹操作"""
        try:
            folder_id = folder.get("id", "")
            if not folder_id:
                self._show_error("文件夹ID无效")
                return
            
            response = await self.api_client.delete_folder(folder_id)
            
            if response.get("success"):
                # 刷新文件夹树
                await self.refresh_folder_tree()
                self._show_success("文件夹删除成功")
            else:
                error_message = response.get("error", {}).get("message", "删除失败")
                self._show_error(f"删除失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Delete folder error: {e}")
            self._show_error(f"删除文件夹失败: {e}")
    
    async def _show_content_preview(self, content_data: Dict[str, Any]) -> None:
        """显示内容预览"""
        # TODO: 实现内容预览
        self._show_info("内容预览功能开发中...")
    
    async def _perform_download(self, content_id: str) -> None:
        """执行下载操作"""
        try:
            response = await self.api_client.download_content(content_id)
            
            if response.get("success"):
                download_url = response.get("data", {}).get("download_url")
                file_name = response.get("data", {}).get("file_name")
                
                if download_url and file_name:
                    self._show_success(f"下载链接已生成: {file_name}")
                else:
                    self._show_error("下载信息不完整")
            else:
                error_message = response.get("error", {}).get("message", "下载失败")
                self._show_error(f"下载失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Download error: {e}")
            self._show_error(f"下载失败: {e}")
    
    async def _perform_delete(self, content_id: str) -> None:
        """执行删除操作"""
        try:
            response = await self.api_client.delete_content(content_id)
            
            if response.get("success"):
                # 从状态管理器中移除
                await self.state_manager.remove_content(content_id)
                
                # 刷新列表
                await self.load_folder_contents(self.selected_folder.get("id", ""))
                
                self._show_success("内容删除成功")
            else:
                error_message = response.get("error", {}).get("message", "删除失败")
                self._show_error(f"删除失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Delete error: {e}")
            self._show_error(f"删除失败: {e}")
    
    # UI辅助方法
    def _set_loading_state(self, is_loading: bool) -> None:
        """设置加载状态"""
        self.is_loading = is_loading
        
        # 这里可以显示/隐藏加载指示器
        if is_loading:
            self.page.show_snack_bar(
                ft.SnackBar(
                    content=Row([
                        ProgressRing(width=16, height=16, stroke_width=2),
                        Text("加载中..."),
                    ], spacing=10),
                    duration=None,
                )
            )
        else:
            self.page.close_snack_bar()
    
    def _show_error(self, message: str) -> None:
        """显示错误消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.ERROR),
                bgcolor=colors.ERROR_CONTAINER,
                duration=4000,
            )
        )
    
    def _show_success(self, message: str) -> None:
        """显示成功消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.GREEN),
                bgcolor=colors.GREEN_CONTAINER,
                duration=3000,
            )
        )
    
    def _show_info(self, message: str) -> None:
        """显示信息消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message),
                duration=2000,
            )
        )
    
    def _show_confirm_dialog(self, title: str, content: str, on_confirm: callable) -> None:
        """显示确认对话框"""
        def handle_confirm(e):
            dialog.open = False
            self.page.update()
            on_confirm(True)
        
        def handle_cancel(e):
            dialog.open = False
            self.page.update()
            on_confirm(False)
        
        dialog = AlertDialog(
            title=Text(title),
            content=Text(content),
            actions=[
                TextButton("取消", on_click=handle_cancel),
                TextButton("确定", on_click=handle_confirm),
            ],
            actions_alignment=ft.MainAxisAlignment.END,
        )
        
        self.page.dialog = dialog
        dialog.open = True
        self.page.update()